package com.parlons.activities;

/**
 * Created by wangyifan on 15/12/24.
 */

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.parlons.DatabaseServices;
import com.parlons.R;
import com.parlons.SmackServices;
import com.parlons.SwipeListView;

@SuppressLint("NewApi")
public class ChatFragment extends Fragment {
    private static SwipeListView chatList;
    public static ChatCursorAdapter simpleCursorAdapter;

    private onRightItemClickListener mListener = null;

    public void setOnRightItemClickListener(onRightItemClickListener listener) {
        mListener = listener;
    }

    public interface onRightItemClickListener {
        void onRightItemClick(View v, int position);
    }


    public class ChatCursorAdapter extends SimpleCursorAdapter {
        private LayoutInflater mLayoutInflater;
        private Context context;
        private int layout;
        private Context mContext = null;
        private int mRightWidth = 0;


        private class ViewHolder {
            TextView usernameView;
            TextView contentView;
            TextView unreadTxt;
            ImageView unreadPoint;
            ImageView avatarView;
            RelativeLayout itemRight;
            TextView itemRightTxt;

            ViewHolder(View v) {
                usernameView = (TextView) v.findViewById(R.id.chat_list_username);
                contentView = (TextView) v.findViewById(R.id.chat_list_content);
                avatarView = (ImageView) v.findViewById(R.id.chat_list_avatar);
                itemRight = (RelativeLayout) v.findViewById(R.id.item_right);
                itemRightTxt = (TextView) v.findViewById(R.id.item_right_txt);
                unreadPoint = (ImageView) v.findViewById(R.id.chat_list_point);
                unreadTxt = (TextView) v.findViewById(R.id.chat_list_unread_number);

            }
        }

        public ChatCursorAdapter(Context ctx, int layout, Cursor c, String[] from, int[] to, int flag) {
            super(ctx, layout, c, from, to, flag);
            this.context = ctx;
            this.layout = layout;
            mContext = ctx;
            mRightWidth = ChatActivity.dip2px(getActivity(), 80);
            mLayoutInflater = LayoutInflater.from(ctx);
        }

        private onRightItemClickListener mListener = null;

        public void setOnRightItemClickListener(onRightItemClickListener listener) {
            mListener = listener;
        }


        @Override
        public View newView(Context ctx, Cursor cursor, ViewGroup parent) {
            View vView = mLayoutInflater.inflate(layout, parent, false);
            vView.setTag(new ViewHolder(vView));
            return vView;// **EDITED:**need to return the view
        }

        @Override
        public void bindView(View v, Context ctx, Cursor c) {
            int iCol_User = c.getColumnIndex("friend_username");
            int iCol_Unread = c.getColumnIndex("unread_number");
            int iCol_Content = c.getColumnIndex("last_message");


            final String sFriendUser = c.getString(iCol_User);
            String sContent = c.getString(iCol_Content);
            int iUnread = c.getInt(iCol_Unread);
            String sUnread = "";
            sUnread += (iUnread <= 99) ? iUnread : ("99+");

            ViewHolder vh = (ViewHolder) v.getTag();

            vh.usernameView.setText(sFriendUser);
            vh.contentView.setText(sContent);
            vh.itemRightTxt.setText("Delete");
            System.out.println("unread: " + sUnread);
            if (!sUnread.equals("0")) {
                vh.unreadTxt.setText(sUnread);
                vh.unreadTxt.setVisibility(View.VISIBLE);
                vh.unreadPoint.setVisibility(View.VISIBLE);
            } else {
                vh.unreadPoint.setVisibility(View.INVISIBLE);
                vh.unreadTxt.setVisibility(View.INVISIBLE);
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(mRightWidth, LinearLayout.LayoutParams.MATCH_PARENT);
            vh.itemRight.setLayoutParams(lp);
            vh.itemRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        mListener.onRightItemClick(v, ChatActivity.dip2px(getActivity(), 80));


                    }
                }
            });

        }

    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(com.parlons.R.layout.chat_list, container, false);
        chatList = (SwipeListView) view.findViewById(R.id.chat_list);//得到ListView对象的引用 /*为ListView设置Adapter来绑定数据*/

        final DatabaseServices DBService = DatabaseServices.getInstance(getActivity());

        long totalUnread = DBService.getTotalUnread(SmackServices.getUserName());
        System.out.println("total unread : " + totalUnread);
        if (totalUnread != 0)
            MainActivity.hasUnread = true;
        else
            MainActivity.hasUnread = false;
        MainActivity.fragmentManager.invalidateOptionsMenu();

        Cursor cursor = DBService.getChatCursor(SmackServices.getUserName());
        simpleCursorAdapter = new ChatCursorAdapter(getActivity(), R.layout.chat_item, cursor, new String[]{"friend_username", "last_message", "unread_number"}, new int[]{R.id.chat_list_username, R.id.chat_list_content, R.id.chat_list_unread_number}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        System.out.println("!!!!!!!!!!!! chat list adapter added");
        chatList.setAdapter(simpleCursorAdapter);//为ListView绑定适配器
        chatList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                SQLiteCursor cursor = (SQLiteCursor) chatList.getItemAtPosition(arg2);
                System.out.println("getCount " + cursor.getCount());
                for (String name : cursor.getColumnNames())
                    System.out.println("names: " + name);
                System.out.println("names: " + cursor.getColumnName(1)); // cursor index starts from 0. here _id, friend_username, last_message
                DBService.resetUnread(SmackServices.getUserName(), cursor.getString(1));


                Intent i = new Intent(getActivity(), ChatActivity.class);
                i.putExtra("friendName", cursor.getString(1));
                startActivity(i);
                // check if the total unread is 0 now...
                MainActivity.fragmentManager.invalidateOptionsMenu();
                System.out.println(arg2);
            }
        });

        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}
